Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 自定义导航栏距离窗口顶部的间距
    navTop: 0,
    // 自定义导航栏宽度
    navWidth: 0,
    // 自定义导航栏高度
    navHeight: 0,
    // 门店信息
    store: {},
    banners: [
      "/images/images/banners/a.png",
      "/images/images/banners/b.png",
      "/images/images/banners/c.png"
    ],
    categories: [{
      id: 1,
      image: "/images/images/Newapp.png",
      content: "福气满满",
      active: true,
      ad: "/images/images/YHQzs.jpg",
      childlist: [{
        id: 11,
        image: "/images/images/Newapp.png",
        title: "福气随心选",
        txt: "热门饮品，任选2杯",
        price: "14.90",
      }, {
        id: 12,
        image: "/images/images/Newapp.png",
        title: "'芋'见福套餐",
        txt: "奶茶",
        price: "16.00",
      }]
    }, {
      id: 2,
      image: "/images/images/Newapp.png",
      content: "蜜雪经典",
      active: false,
      ad: "/images/images/YHQzs.jpg",
      childlist: [{
        id: 13,
        image: "/images/images/Newapp.png",
        title: "0000",
        txt: "热门饮品，任选121杯",
        price: "666.666",
      }, {
        id: 14,
        image: "/images/images/Newapp.png",
        title: "123",
        txt: "热门饮品，任选3杯",
        price: "993.1",
      }]
    }, {
      id: 3,
      image: "/images/images/Newapp.png",
      content: "新品来袭",
      ad: "/images/images/YHQzs.jpg",
      active: false,
      childlist: [{
        id: 15,
        image: "/images/images/Newapp.png",
        title: "010",
        txt: "热门饮品，任选121杯",
        price: "666.666",
      }, {
        id: 16,
        image: "/images/images/Newapp.png",
        title: "5t23",
        txt: "热门饮品，任选3杯",
        price: "993.1",
      }]
    }, {
      id: 4,
      image: "/images/images/Newapp.png",
      content: "福气满满11",
      active: false,
      ad: "/images/images/YHQzs.jpg",
      childlist: [
        {
          id: 21,
          title: '冰鲜柠檬水',
          txt: '大片柠檬看得见, 现切现捣',
          price: 4.9,
          image: '/images/images/Newapp.png',
        },
        {
          id: 22,
          title: '新鲜冰淇淋',
          txt: '新鲜冰淇淋, 一口就爱上',
          price: 2.9,
          image: '/images/images/Newapp.png',
        },
        {
          id: 23,
          title: '珍珠奶茶',
          txt: '珍珠奶茶Q弹, 奶茶经典',
          price: 6.9,
          image: '/images/images/Newapp.png',
        },
      ]
    }, {
      id: 5,
      image: "/images/images/Newapp.png",
      content: "福气满23满",
      ad: "/images/images/YHQzs.jpg",
      active: false
    }, {
      id: 6,
      image: "/images/images/Newapp.png",
      content: "福4气满满",
      ad: "/images/images/YHQzs.jpg",
      active: false
    }, {
      id: 7,
      image: "/images/images/Newapp.png",
      content: "123福气满满",
      ad: "/images/images/YHQzs.jpg",
      active: false
    }],
    active: 0,
    // 视图滚动ID
    scrollIntoViewId: "",
    // 保存加入购物车的饮品数据
    cart: [],
    // 购物车总数
    totalAmount: 0,
    // 购物车总额
    totalPrice: 0,
    // 是否显示购物车的明细
    showDetail: false
  },

  // 跳转门店列表
  handleJumpToList() {
    wx.navigateTo({
      url: '/pages/list/index',
    })
  },

  // 处理切换分类
  handleActive(event) {
    const index = event.currentTarget.dataset.index;
    // 设置左侧菜单栏
    this.setData({
      active: index
    })
    // 设置右侧滚动视图
    this.setData({
      scrollIntoViewId: `goods-${index}`
    })
  },

  // 加入购物车
  handleAddCard(event) {
    // 判断用户是否的登录
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.navigateTo({
        url: '/pages/login/index',
      });
      return;
    }
    // 加入购物车
    const goods = event.target.dataset;
    console.log("当前选购：", goods);
    // 若购物车有了该商品
    const findData = this.data.cart.some(item => item.id === goods.id);
    const cart = [...this.data.cart];
    if (findData) {
      cart.forEach(item => {
        if (item.id === goods.id) {
          item.amount++;
        }
      });
    } else {
      cart.push({
        ...goods,
        amount: 1
      })
    }

    this.setData({
      cart: cart
    });

    wx.showToast({
      title: '成功',
      icon: 'success',
      duration: 1000
    });

    // 计算购物车结果
    this.calcTotal();
  },

  // 计算
  calcTotal() {
    // 计算总数
    const totalAmount = this.data.cart.reduce((sum, item) => sum + item.amount, 0);
    // 计算总金额
    const totalPrice = this.data.cart.reduce((sum, item) => sum + item.price * item.amount, 0).toFixed(2);
    this.setData({
      totalAmount: totalAmount,
      totalPrice: totalPrice
    })
  },

  /**
   * 切换显示购物车
   */
  handleDetail() {
    this.setData({
      showDetail: !this.data.showDetail
    })
  },

  /**
   * 修改购物车数量 
   */
  handleAmountChange(event) {
    const { type, id } = event.target.dataset;
    const cart = this.data.cart.map(item => {
      if (item.id === id) {
        item.amount += type == "plus" ? 1 : -1;
      }
      return item;
    }).filter(item => item.amount > 0);

    this.setData({
      cart
    })

    // 重新统计
    this.calcTotal()

    // 判断是否全部删除
    if (cart.length == 0) {
      this.setData({
        showDetail: false
      })
    }
  },

  /**
   * 清空购物车
   */
  handleClearCart() {
    wx.showModal({
      title: '提示',
      content: '确认清空购物车吗？',
      complete: (res) => {
        // 取消
        if (res.cancel) {
          return;
        }
        // 确定
        if (res.confirm) {
          this.setData({
            cart: [],
            showDetail: false
          })
        }
      }
    })
  },

  /**
   * 确认订单
   */
  handleConfirm(){
      // 全部结算发送后端保存订单信息

      //TODO

      // 结算后商品清空
      this.setData({
        cart: [],
        showDetail: false
      })

      wx.switchTab({
        url: '/pages/order/index',
      })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取右上角胶囊信息
    const { top, left, height } = wx.getMenuButtonBoundingClientRect();
    this.setData({
      navTop: top,
      navWidth: left - 20,
      navHeight: height
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log("页面显示")
    // 判断是否进入代餐页面时,是否有选择门店列表的信息
    const info = wx.getStorageSync('store-info');
    if (!info) {
      wx.navigateTo({
        url: '/pages/list/index',
      });
    }
    this.setData({
      store: info
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log("页面隐藏")

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log("页面卸载")
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})